package top.jiangqiang.qianyi.common.convert;

import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Component;
import top.jiangqiang.qianyi.common.exception.Error500Exception;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Component
public class TypeConverter {

    private final ConversionService conversionService;

    /**
     * 对象类型转换
     *
     * @param source    源对象
     * @param distClass 目标类型
     * @return 目标类型的对象
     */
    public <S, D> D convert(@NotNull S source, @NotNull Class<D> distClass) {
        try {
            return conversionService.convert(source, distClass);
        } catch (Exception e) {
            log.warn(e.getMessage());
            log.error("没有对应的mapstruct转换器:{}=>{}", source.getClass().getSimpleName(), distClass.getSimpleName());
            throw new Error500Exception(e);
        }
    }

    /**
     * 转换集合类型
     *
     * @return
     */
    public <S, D> List<D> convertList(@NotNull Collection<S> sourceCollection, @NotNull Class<D> clazz) {
        return sourceCollection.stream().map(item -> convert(item, clazz)).toList();
    }

    public <S, D> List<D> convertList(@NotNull S[] sourceArray, @NotNull Class<D> clazz) {
        return Arrays.stream(sourceArray).map(item -> convert(item, clazz)).toList();
    }

}
